/* eslint-disable prefer-destructuring */
import dictApi from '@/api/modules/system/dict'
import i18n from '@/lang'
function getDictCodeInitVal (key) {
  const data = sessionStorage.getItem(key)
  if (data) {
    return JSON.parse(data)
  }
  return []
}
const apis = [
  'getStrategyUpgradeTypeDictCodes',
  'getStrategyDownloadNetworkDictCodes',
  'getStrategySpeedLimitDictCodes',
  'getStrategyHandbrakeLimitDictCodes',
  'getStrategyPowerLimitDictCodes',
  'getStrategyParkLimitDictCodes',
  'getStrategyEngineSpeedLimitDictCodes',
  'getStrategySceneTypeDictCodes',
  'getAuditCategoryDictCodes',
  'getStrategyStatusDictCodes',
  'getTaskVehicleStatusDictCodes',
  'getAuditItemStatusDictCodes',
  'getAuditStatusDictCodes',
  'getVehicleDataTypeDictCodes',
  'getTheftPreventionStatusDictCodes',
  'getDoorStatusDictCodes',
  'getChargeStatusDictCodes',
  'getObdStatusDictCodes',
  'getEngineStatusDictCodes',
  'getAdditionalClauseTypeDictCodes',
  'getLastActiveDictCodes',
  'getLastUpgradeSuccessDictCodes',
  'getVehicleStatusDictCodes',
  'getTaskOperationTypeDictCodes',
  'getTaskVehicleUpgradeStatusDictCodes',
  'getStrategyTestingDictCodes',
  'getSystemLogTypeDictCodes',
  'getEcuReprogramTypeDictCodes',
  'getEcuReprogramWayDictCodes',
  'getEcuUpdateStyleDictCodes',
  'getHvPowerFlagDictCodes',
  'getHlvFlagDictCodes',
  'getClientLogTypeDictCodes',
  'getDllNameDictCodes',
  'getEcuEncryptTypeDictCodes',
  'getFileStatusDictCodes',
  'getResourceStateDictCodes',
  'getServiceSaleCateFlagDictCodes',
  'getServiceSaleExamCodeDictCodes',
  'getServiceSaleBelongFlagDictCodes',
  'getServicePublishStatusDictCodes',
  'getServiceOrderStatusDictCodes',
  'getSubsServiceStatusDictCodes',
  'getOrderRefundStatusDictCodes',
  'getThirdSupplierDictCodes',
  'getOtaUpdateTypeDictCodes',
  'getTaskEcuUpdateDictCodes',
  'getTaskUpdateDictCodes',
  'getProvinceDictCodes',
  'getConfigModelDataFromDictCodes',
  'getCompanyDictCodes',
  'getPowerTypeDictCodes',
  'getSaleAreaDictCodes',
  'getProvinceDictCodes',
  'getProducePhaseDictCodes',
  'getManufacturerDictCodes',
  'getFactoryChannelDictCodes',
  'getVersionTypeDictCodes',
  'getUpgradeTriggerTypeDictCodes',
  'getDiLinkVersionDictCodes',
  'getGcyOtaUpdateScopeDictCodes',
  'getGcyOtaSupplierVerifyResultDictCodes',
  'getBusinessTypeDictCodes',
  'getFactoryChannelDictCodes',
  'getImportTaskVehicleStatusDictCodes',
  'getBinlocationDictCodes',
  'getPlatformDictCodes',
  'getTaskGcyAuditStatusDictCodes',
  'getEmailMessageTemplateBusinessTypeDictCodes',
  'getEcuChangeOriginDictCodes',
  'getVehicleTypeDictCodes',
  'getUpgradeTypeDictCodes',
  'getErrorLogTypeDictCodes',
  'getLoopTestTaskStatusDictCodes',
  'getSoftwareMakeStatusDictCodes',
  'getSoftwareMakeTypeDictCodes',
  'getDllClassNameDictCodes',
]

const dictConfigs = {
  state: {},
  actions: {}
}
// 动态生成state及actions
apis.forEach((item) => {
  const reg = /^get([a-zA-Z]+)DictCodes$/
  const match = item.match(reg)
  const key = match[1]
  if (!key) {
    return
  }
  const stateKey = key.charAt(0).toLowerCase() + key.slice(1) + 'DictCode'
  dictConfigs.state[stateKey] = getDictCodeInitVal(stateKey)
  const method = 'get' + key + 'DictCodeData'
  dictConfigs.actions[method] = ({ commit, state }) => {
    if (state[stateKey].length) {
      //cjf 221021 无更新机制，暂不从缓存读取
      // return false
    } 
    // eslint-disable-next-line consistent-return
    return new Promise((resolve, reject) => {
      let dictGet = dictApi[item];
      if (!dictGet) {
        dictGet = () => {
          return dictApi.getDictCodeByKey(key.charAt(0).toLowerCase() + key.slice(1))
        }
      }
      dictGet().then(res => {
        commit('SET_DICT_CODE', { key: stateKey, val: res.data })
        resolve(res.data)
      }).catch(err => {
        reject(err)
      });
    })
  }
})
const oneWeekDays = []
for (let i = 1; i < 8; i = i + 1) {
  oneWeekDays.push({
    value: i + '',
    name: i18n.t('day' + i)
  })
}
const state = {
  // 字典项列表查询参数 
  queryParamsDict: {
    dictCode: ''
  },
  ...dictConfigs.state,
  // 零件升级状态
  taskEcuUpdateDictCode: getDictCodeInitVal('taskEcuUpdateDictCode'),
  // 任务升级状态
  taskUpdateDictCode: getDictCodeInitVal('taskUpdateDictCode'),
  // 追加车辆状态
  importTaskVehicleStatusDictCode: getDictCodeInitVal('importTaskVehicleStatusDictCode'),
  // 任务状态集合对应的图标及颜色
  taskUpdateStateObj: {
    '6': {
      iconPig: 'butongcuxideyuanhuan',
      color: '#4388A6',
      echartsColor: '#5470C6'
    },
    '7': {
      iconPig: 'butongguo',
      color: '#EE6666'
    },
    '11': {
      iconPig: 'weikaishi',
      color: '#91CC75'
    },
    '12': {
      iconPig: 'zhengzaijinxing',
      color: '#3BA272'
    },
    '13': {
      iconPig: 'guaqi',
      color: '#FC8452'
    },
    '16': {
      iconPig: 'quxiao',
      color: '#FAC858'
    },
    '17': {
      iconPig: 'jieshu',
      color: '#73C0DE'
    },
    '18': {
      iconPig: 'quxiao',
      color: '#2b2b2b'
    }
  },
  // 服务发布状态颜色
  servicePublishStateObj: {
    '-1': {
      color: '#68748B'
    },
    '0': {
      color: '#FDC673'
    },
    '3': {
      color: '#5470C6'
    },
    '5': {
      color: '#FF8762'
    },
    '6': {
      color: '#46D5A2'
    },
    '7': {
      color: '#8A8A8A'
    },
    '20': {
      color: '#2BB080'
    }
  },
  // 升级包类型
  packageTypes: [{
    value: '1',
    name: i18n.t('totalPackage')
  }, {
    value: '2',
    name: i18n.t('differentialPackage')
  }],
  switchTypes: [{
    value: '1',
    name: i18n.t('open'),
    id: 1
  },
  {
    value: '0',
    name: i18n.t('close'),
    id: 2
  }],
  // 提醒日
  reminderWeekDays: oneWeekDays,
  // 提醒时段
  reminderPeriods: [{
    id: 1,
    value: '8:00~10:00'
  }, {
    id: 2,
    value: '10:00~12:00'
  }, {
    id: 3,
    value: '12:00~14:00'
  }, {
    id: 4,
    value: '14:00~16:00'
  }, {
    id: 5,
    value: '16:00~18:00'
  }, {
    id: 6,
    value: '18:00~20:00'
  }],
  // 摘要算法
  digestAlgorithm: {
    1: 'MD5',
    2: 'SHA256'
  },
  // ecu在车型上安装情况
  ecuAssembleTypeOptions: [{
    id: 1,
    name: 'none',
    value: 0
  },{
    id: 2,
    name: 'standardConfig',
    value: 1
  }, {
    id: 3,
    name: 'optional',
    value: 2
  }]
}
const mutations = {
  SET_DICT_CODE (state, { key, val }) {
    if (typeof state[key] !== 'undefined') {
      // eslint-disable-next-line no-param-reassign
      state[key] = val
      sessionStorage.setItem(key, JSON.stringify(val))
    }
  }
}
const actions = {
  ...dictConfigs.actions,
  // eslint-disable-next-line no-unused-vars
  removeAllDictCode ({ state, commit }) {
    apis.forEach(item => {
      let key = item.replace('get', '')
      key = key.charAt(0).toLowerCase() + key.slice(1, -1)
      sessionStorage.removeItem(key)
      commit('SET_DICT_CODE', { key, val: [] })
      console.log(sessionStorage.getItem(key), '0009999')
    })
  }
}

const getters = {
  // 将字典列表转换成对象形式{value1=>code1,value2=>code2...}
  getDictCodeObj: state => dictCodeKey => {
    const obj = {}
    state[dictCodeKey].forEach(item => {
      obj[item.value] = item.name
    })
    return obj
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}
